package tc.alert.tckejisoc.rule;

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.PathNotFoundException;
import lombok.extern.slf4j.Slf4j;
/**
 * author: cyq
 * time: 2024/10/23 17:37
 */
@Slf4j
public class JsonPathMapping implements FieldMapping {
    private final String target;
    private JsonPath jsonPath;

    public JsonPathMapping(String target, String jsonPath) {
        this.target = target;
        this.jsonPath = JsonPath.compile(jsonPath);
    }

    String  a ="$.asd[s]";
    @Override
    public String extractValue(String rawLog) {
        try {
            String path = jsonPath.getPath();
            if (path.contains("|")) {
                String replace = path.replace("|", "'],$['");
                String[] split = replace.split(",");
                for (int i = 0; i < split.length; i++) {
                    jsonPath = JsonPath.compile(split[i]);
                    try {
                        Object read = jsonPath.read(rawLog);
                        if (null != read) {
                            return read.toString();
                        }
                    } catch (Exception e) {
                        log.debug("多条件下没有找到数据");
                    }


                }
            } else {

                Object result = jsonPath.read(rawLog);
                return result != null ? result.toString() : "";
            }
            return "";
        } catch (PathNotFoundException e) {
            return "";
        }
    }

    @Override
    public String getTarget() {
        return target;
    }
}